# -*-coding:utf-8-*-
#Import sessions for session handling
import webapp2
from webapp2_extras import sessions
from webapp2_extras import auth
import json
from BiyiModel.UserModel import BiyiUser
from google.appengine.ext import db
#This is needed to configure the session secret key
#Runs first in the whole application
sessionconfig = {}
sessionconfig['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key-somemorearbitarythingstosay',
}
sessionconfig['webapp2_extras.auth'] = {
    'user_model': BiyiUser,
}
def login_required(handler):
    "Requires that a user be logged in to access the resource"
    def check_login(self, *args, **kwargs):     
        if not self.user:
            return self.redirect_to('login',rurl=self.request.url);
        else:
            return handler(self, *args, **kwargs)
    return check_login
#Session Handling class, gets the store, dispatches the request
class BaseSessionHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()
    def getUser(self):
        
        return self.userModel;
    @webapp2.cached_property
    def user(self):
        user = self.auth.get_user_by_session()
        return user
    @webapp2.cached_property
    def auth(self):
        return auth.get_auth(request=self.request)
    @webapp2.cached_property
    def userModel(self):
        userModel, timestamp = self.auth.store.user_model.get_by_auth_token(
                self.user['user_id'], 
                self.user['token']) if self.user else (None, None)
        return userModel
    @webapp2.cached_property
    def isAjaxRequest(self):
        if self.request.headers.has_key('X-Requested-With'):
            if self.request.headers['X-Requested-With'] == 'XMLHttpRequest':
                return True;
            else:
                return False;
        else:
            return False;
    def ajaxReturn(self,status=0,msg="success",data=[]):
        self.response.headers['Content-Type']='application/json'
        ret = {}; 
        ret['status'] = status;
        ret['msg'] = msg;
        ret['data']= data;
        jsontao = json.dumps(ret);
        self.response.out.write(str(jsontao).decode('utf-8'))
#End of BaseSessionHandler Class
